const { md5 } = require("utility")
const query = require("../db/mysql")
const jwt = require("jsonwebtoken")
const { error, success } = require("../module/module")
class Login {
    //登陆
    login = async (ctx) => {
        let { userName, passWord } = ctx.request.body
        let sql = 'select * from user_list where 1=1 '
        console.log(userName.length)
        if (userName.length) {
            sql += `and userName="${userName}" and passWord="${md5(String(passWord))}" `
            let data = await query(sql)
            if (data.length) {
                let token = jwt.sign({ id: data[0].id }, '1812b')
                ctx.body = success({ data, token }, '登陆成功')
            } else {
                ctx.body = error('账号密码错误')
            }
        }



    }
    //注册
    register = async (ctx) => {
        let { userName, passWord, nicName } = ctx.request.body
        console.log(userName, passWord)
        let userSql = `select * from user_list where 1=1  and userName="${userName}" `
        let isHave = await query(userSql)
        if (isHave.length) {
            ctx.body = error('已存在此用户')
        } else {
            let sql = `insert into user_list (userName, passWord, nicName) values ("${userName}","${md5(String(passWord))}","${nicName}") `
            let data = await query(sql)
            if (data.affectedRows === 1) {
                ctx.body = success(data, '注册成功')
            } else {
                ctx.body = error('注册失败')
            }
        }
    }
}

module.exports = new Login()